# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import hashlib
import time

YOUDAO_URL = 'https://openapi.youdao.com/ttsapi'
APP_KEY = '你的的应用ID'
APP_SECRET = '你的应用密钥'


def encrypt(signStr):
	hash_algorithm = hashlib.md5()
	hash_algorithm.update(signStr.encode('utf-8'))
	return hash_algorithm.hexdigest()


def truncate(q):
	if q is None:
		return None
	size = len(q)
	return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def do_request(data):
	headers = {'Content-Type': 'application/x-www-form-urlencoded'}
	return requests.post(YOUDAO_URL, data=data, headers=headers)


def connect():
	q = "你要合成的英文."
	name = "保存的文件名"		# 文件名
	data = {}
	data['langType'] = 'en'		# 要合成的语言类型
	salt = str(uuid.uuid1())
	signStr = APP_KEY + q + salt + APP_SECRET
	sign = encrypt(signStr)
	data['appKey'] = APP_KEY
	data['q'] = q
	data['salt'] = salt
	data['sign'] = sign
	data['speed'] = 1

	response = do_request(data)
	contentType = response.headers['Content-Type']
	if contentType == "audio/mp3":
		print("成功")
		millis = int(round(time.time() * 1000))
		filePath = name + str(millis) + ".mp3"
		fo = open(filePath, 'wb')
		fo.write(response.content)
		fo.close()
	else:
		print("类型错误", response.content)


if __name__ == '__main__':
	connect()
